package com.study.controller;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.ChannelOption;
import io.netty.util.internal.SocketUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.study.handler.UdpServerHandler;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
@RequestMapping("/udpClient")
public class UdpClientController {

    @Value("${gps.netty.tcp.server}")
    private String serverIp;
    @Value("${gps.netty.udp.port}")
    private int port;



    @PostMapping("sendUdp")
    public String send(String msg){
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        Channel ch =null;
        UdpServerHandler handler=new UdpServerHandler();

        try {
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<NioDatagramChannel>() {

                        @Override
                        protected void initChannel(NioDatagramChannel ch) throws Exception {
                            ch.pipeline().addLast(handler.getClass().getSimpleName(),handler);
                        }});
            ch =b.bind(0).sync().channel();
        } catch (Exception e) {
            e.printStackTrace();
        }

        ByteBuf buf = Unpooled.copiedBuffer(msg.getBytes(StandardCharsets.UTF_8));

        try{
            log.info("UDP客户端发送消息：{}", msg);
            ch.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer(buf.array()),
                    SocketUtils.socketAddress(serverIp, port))).sync();
        }catch (Exception e){
            log.info("UDP客户端发送消息失败：{}", e);
        }

        //关闭链接
        group.shutdownGracefully();
        return "success";
    }
}
